import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
import {Validators, FormBuilder} from '@angular/forms';

@Component({
  selector: 'app-homework-list',
  templateUrl: './homework-list.component.html',
  styleUrls: ['./homework-list.component.scss']
})
export class HomeworkListComponent implements OnInit {
  constructor(private http: HttpClient, private formBuilder: FormBuilder, private modalService: NgbModal) {
  }
  // 作业列表
  public workList: any;
  public search = {
    workName: ''
  };
  page = {
    pageIndex: 1,
    pageSize: 10,
    total: 0,
  };
  workType = 1;
  workForm = this.formBuilder.group({
    courseid: [1, Validators.required],
    work_name: ['', Validators.required],
    deadline :  ['', Validators.required],
    centent: ['', Validators.required],
    id: [''],
    status: [0, Validators.required],
  });
  ngOnInit(): void {
    this.initData();
  }
  /*
  * 初始化请求
  * */
  initData(): void {
    this.http.post('/api/selectWork', this.search, {headers: {'Content-Type': 'application/json'}})
      .subscribe((res: any) => {
        this.workList = res || [];
        this.page.total = this.workList.length;
      });
  }
  /*
  * 条件查询
  * */
  search_work(): void {
    this.initData();
  }
  /*
  * 修改弹框
  * */
  showWorkModel(type: number, content: any, data: any): void {
    this.workType = type;
    if (type === 2){
      this.workForm.patchValue({
        courseid: data.courseid,
        work_name: data.work_name,
        deadline: data.deadline,
        centent: data.centent,
        id: data.id,
        status: data.status,
      });
    } else{
      this.workForm.patchValue({
        courseid: 1,
        work_name: '',
        deadline: '',
        centent: '',
        id: '',
        status: 0,
      });
    }
    this.modalService.open(content, {size: 'lg', ariaLabelledBy: 'modal-basic-title'});
  }
  /*
  * 删除
  * */
  delWork(data: object): void{
    // @ts-ignore
    const {id} = data;
    const $confirm = window.confirm('确定要删除当前作业吗？');
    if ($confirm){
      this.http.post('/api/deleteWork', {id}, {headers: {'Content-Type': 'application/json'}})
       .subscribe((res: any) => {
         this.initData()
         window.alert('删除成功');
       });
    }
  }
  /*
  * 保存作业信息
  * */
  saveWork(): void{
  }
  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return 'by pressing ESC';
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return 'by clicking on a backdrop';
    } else {
      return `with: ${reason}`;
    }
  }
}
